<template>
  <BasicDrawer
    @register="registerDrawer"
    :showFooter="showFooter"
    :title="getTitle"
    @ok="handleSubmit"
    :canFullscreen="false"
    width="900px"
  >
    <BasicForm @register="registerForm" class="menuForm">
      <template #reqMethod="{ field }">
        <span>POST</span>
      </template>
      <template #add="{ model, field }">
        <div class="addCol">
          <a-button shape="circle" type="primary" preIcon="ant-design:plus-outlined" @click="handleOpenExtendFieldsModal(model)" class="addBtn" :disabled="!showFooter">
            &nbsp;
          </a-button>
          添加字段属性
        </div>
      </template>
      <template #del="{ model, field }">
        <div class="addColInput">
          <a-input v-model:value="model[field]" />
          <a-button @click="delExtendFields(field)" class="delBtn">-</a-button>
        </div>
      </template>
      <template #table="{ field }">
        <div style="margin-left: 140px; width: 100%">
          <BasicTable @register="registerTable" :dataSource="mapping.items">
            <template #action="{ index, record }">
              <TableAction :actions="getActions(index, record)" />
            </template>
          </BasicTable>
        </div>
      </template>
      <template #addTopic="{ model, field }">
        <div class="addCol">
          <a-button preIcon="ant-design:plus-outlined" class="addTopicBtn" @click="handleOpenMappingModal" :disabled="!showFooter">新增</a-button>
        </div>
      </template>
    </BasicForm>

    <BasicModal
      @register="registerExtendFieldsModal"
      title="指令消费配置项"
      @ok="handleAddExtendField"
      @cancel="handleCancelExtendField"
      :height="120"
      :bodyStyle="{ marginLeft: '100px' }"
      :canFullscreen="false"
    >
      <BasicForm @register="registerExtendFieldForm" />
    </BasicModal>

    <BasicModal @register="registerMappingModal" title="新增主题映射" @ok="handleAddMapping" @cancel="handleCancelMapping" :height="210" :canFullscreen="false">
      <BasicForm @register="registerMappingForm" />
    </BasicModal>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, reactive, computed, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { extendFormFieldOptions, formSchema, extendFieldFormSchema, mappingFormSchema, columns } from './instruct.data';
  import { getInstructById, saveOrUpdateInstruct } from './instruct.api';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  const isUpdate = ref(true);
  const mapping = reactive({
    items: [],
  });
  const command = ref();
  const selectedExtendFields = ref([]);
  const emit = defineEmits(['success', 'register']);
  const [registerExtendFieldsModal, { openModal: openExtendFieldsModal, closeModal: closeExtendFieldsModal }] = useModal();
  const [registerMappingModal, { openModal: openMappingModal, closeModal: closeMappingModal }] = useModal();
  const [registerForm, { removeSchemaByFiled, appendSchemaByField, resetFields, setFieldsValue, validate, setProps }] = useForm({
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    labelWidth: 140,
    // compact: true,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const [registerExtendFieldForm, { validate: validateExtendField, resetFields: resetFieldsExtend }] = useForm({
    schemas: [
    {
      label: '',
      field: 'params',
      component: 'Select',
      componentProps: ({ formModel }) => {
        return {
          placeholder: '请输入属性名',
          options: filteredExtendFormFieldOptions(command.value, selectedExtendFields.value),
          getPopupContainer: () => document.body,
        };
      },
    },
  ],
    showActionButtonGroup: false,
  });
  const [registerMappingForm, { validate: validateMapping, resetFields: resetMappingFields }] = useForm({
    labelWidth: 100,
    schemas: mappingFormSchema,
    showActionButtonGroup: false,
  });
  const showFooter = ref(true);
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    if(selectedExtendFields.value && selectedExtendFields.value.length>0){
      selectedExtendFields.value.forEach((item)=>{
        removeSchemaByFiled([`${item}`]);
      });
      selectedExtendFields.value = [];
    }
    mapping.items = [];

    showFooter.value = data?.showFooter ?? true;
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      //获取详情
      data.record = await getInstructById({ id: data.record.id });
      if(data.record.mapping){
        mapping.items = [...data.record.mapping.items];
      }
      if(data.record.properties){
        for (var item in data.record.properties) {
          data.record[item] = data.record.properties[item];
          const list = formSchema.filter((p)=>p.field == item);
          if (list && list.length <= 0) {
            addExtendFields(item);
          }
        }
      }
    }
    //表单赋值
    await setFieldsValue({
        ...data.record,
    });
    setProps({ disabled: !data?.showFooter });

    command.value = data.record.command;
  });
  //获取弹窗标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增指令消费' : '编辑指令消费'));

  async function handleOpenExtendFieldsModal() {
    openExtendFieldsModal(true, {});
    nextTick(()=>{
      resetFieldsExtend();
    });
  }

  async function handleOpenMappingModal() {
    openMappingModal(true, {});
    nextTick(()=>{
      resetMappingFields();
    });
  }

  async function handleAddExtendField() {
    const values = await validateExtendField();
    addExtendFields(values.params);
    closeExtendFieldsModal();
  }

  function handleCancelExtendField() {
    closeExtendFieldsModal();
  }

  async function handleAddMapping() {
    const values = await validateMapping();
    mapping.items = [...mapping.items, values];
    handleCancelMapping();
  }
  
  function handleCancelMapping() {
    closeMappingModal();
  }

  function addExtendFields(field){
    if(!selectedExtendFields.value.includes(field)){
      let prefixField = '';
      if(selectedExtendFields.value.length>0){
        prefixField = selectedExtendFields.value[selectedExtendFields.value.length-1];
      }else{
        const index = formSchema.findIndex((item) => item.field == 'addField');
        const schema = formSchema[index-1];
        if(schema && schema.field){
          prefixField = schema.field;
        }
      }
      
      appendSchemaByField(
        {
          field: field,
          label: field,
          component: 'Input',
          required: true,
          colProps: {
            span: 20,
          },
          slot: 'del',
        },
        prefixField
      );

      selectedExtendFields.value.push(field);
    }
  }

  async function delExtendFields(field) {
    removeSchemaByFiled([`${field}`]);
    let index = selectedExtendFields.value.indexOf(field);
    if (index !== -1) {
      selectedExtendFields.value.splice(index, 1);
    }
  }

  function filteredExtendFormFieldOptions(command, selectedItems) {
    if(extendFormFieldOptions.hasOwnProperty(command)){
      const options = extendFormFieldOptions[command].filter(o => !selectedItems.includes(o.label));
      return options;
    }
    return [];
  }

  const [registerTable] = useTable({
    title: '',
    columns: columns,
    bordered: true,
    actionColumn: {
      width: 100,
      title: 'Action',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  /**
   * 操作列定义
   * @param record
   */
  function getActions(index, record) {
    return [
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, index, record),
        },
      },
    ];
  }
  /**
   * 删除事件
   */
  async function handleDelete(index, record) {
    mapping.items.splice(index, 1);
    mapping.items = [...mapping.items];
  }

  /**
   * 提交表单事件
   */
   async function handleSubmit() {
    try {
      const values = await validate();
      //主题映射
      values.mapping = { items: [] };
      values.mapping.items = mapping.items;
      //数据源配置
      //1、从divider-properties至addField中的数据
      //2、动态扩展属性
      values.properties = {};
      let flag = false;
      for(let i=0; i<formSchema.length; i++){
        const item = formSchema[i];
        if(!item.ifShow && item.field == 'addField'){
          break;
        }
        if(!flag && item.field == 'divider-properties'){
          flag = true;
        }
        if(flag && values.hasOwnProperty(item.field)){
          values.properties[item.field] =  values[item.field];
          delete values[item.field];
        }
      }
      const extendFields = filteredExtendFormFieldOptions(command.value, []);
      for(let i=0; i<extendFields.length; i++){
        const item = extendFields[i];
        if(values.hasOwnProperty(item.label)){
          values.properties[item.label] = values[item.label];
          delete values[item.label];
        }
      }
      setDrawerProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdateInstruct(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  
  // /**
  //  * 提交表单事件
  //  */
  // async function handleSubmit() {
  //   try {
  //     const values = await validate();
  //     const properties = await validateExtendField();

  //     delete values['anchorField'];

  //     values.mapping = { items: [] };
  //     values.mapping.items = mapping.items;
  //     values.properties = {
  //       'bootstrap.servers': values['bootstrap.servers'],
  //       'group.id': values['group.id'],
  //       'key.deserializer': values['key.deserializer'],
  //       'value.deserializer': values['value.deserializer'],
  //     };
  //     delete values['bootstrap.servers'];
  //     delete values['group.id'];
  //     delete values['key.deserializer'];
  //     delete values['value.deserializer'];
      
  //     if(values['auto.offset.reset']){
  //       values.properties['auto.offset.reset'] = values['auto.offset.reset'];
  //       delete values['auto.offset.reset'];
  //     }
  //     if(values['max.poll.records']){
  //       values.properties['max.poll.records'] = values['max.poll.records'];
  //       delete values['max.poll.records']
  //     }
  //     setDrawerProps({ confirmLoading: true });
  //     //提交表单
  //     await saveOrUpdateInstruct(values);
  //     mapping.items = [];
  //     closeDrawer();
  //     emit('success');
  //   } finally {
  //     setDrawerProps({ confirmLoading: false });
  //   }
  // }
</script>
<style scoped>
  :deep(:where(.css-dev-only-do-not-override-udyjmm).ant-divider-horizontal.ant-divider-with-text) {
    margin: 10px 0;
    font-weight: 700;
  }
  .addCol {
    margin-left: 140px;
  }
  .addBtn {
    margin-right: 20px;
  }
  .addTopicBtn {
    background: linear-gradient(144deg, rgba(18, 76, 255, 0.12), rgba(67, 147, 255, 0.12));
    color: #1d6bff;
  }
  .delBtn {
    margin-left: 20px;
  }
  .addColInput {
    display: flex;
  }
</style>
